package com.junlong0716.enjoylearning.ui

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import com.junlong0716.enjoylearning.MyApp
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.adapter.ChannelListAdapter
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.entity.AudioEntity
import com.junlong0716.enjoylearning.entity.ChannelMultipleItemEntity
import com.junlong0716.enjoylearning.net.api.NetApi
import com.junlong0716.enjoylearning.service.MusicService
import com.junlong0716.enjoylearning.service.PlayerManager
import com.junlong0716.enjoylearning.widget.PlayerBarView
import com.junlong0716.getknowledgedemo.decoration.DividerItemDecoration
import com.junlong0716.module.common.rxbus.RxBus
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_message.*
import kotlinx.android.synthetic.main.view_title_bar.*
import org.json.JSONObject

class MessageActivity : AppCompatActivity() {
    private lateinit var channelListAdapter: ChannelListAdapter
    private lateinit var messages: ArrayList<ChannelMultipleItemEntity>

    private var mPlayerBarView: PlayerBarView? = null
    private var musicService: MusicService? = null
    private var mPlayerManager: PlayerManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_message)
        RxBus.getDefault().register(this)

        rl_back.setOnClickListener { finish() }

        tv_title.text = "我的消息"

        messages = ArrayList()

        srl_refresh.isEnableLoadMore = false

        srl_refresh.autoRefresh()

        srl_refresh.setOnRefreshListener {
            requestMessage()
        }



        bindMusicService()

        rv_list.layoutManager = LinearLayoutManager(this)

        channelListAdapter = ChannelListAdapter(messages)

        rv_list.adapter = channelListAdapter
        rv_list.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL, 4, ContextCompat.getColor(this, R.color.recyclerview_divider_gray)))


        channelListAdapter.setOnItemClickListener { adapter, view, position ->
            when (messages[position].knowledgeType) {
                1 -> {
                    val intent = Intent()
                    intent.setClass(this, VideoActivity::class.java)
                    intent.putExtra("video_url", NetConstant.REQUEST_SOURCE + messages[position].fileAddress)
                    intent.putExtra("video_id", messages[position].id)
                    intent.putExtra("video_author", messages[position].authorName)
                    startActivity(intent)
                }
                2 -> {
//                    val parentActivity = activity as ChannelActivity
//                    if (ServiceUtils.isServiceRunning(MusicService::class.java)) {
//
//                        parentActivity.nextMusic(data[position].id, data[position].fileAddress, data[position].knowledgeTitle, NetConstant.REQUEST_SOURCE + data[position].coverImg)
//                        parentActivity.setPlayState()
//                        RxBus.getDefault().post(AudioLayoutVisibleStateEvent(Constant.AUDIO_LAYOUT_VISIBLE_FLAG, true))
//                        RxBus.getDefault().post(MusicPlayNameEvent(0xff21, data[position].knowledgeTitle, NetConstant.REQUEST_SOURCE + data[position].coverImg))
////                        RxBus.getDefault().post(MusicPlayStateEvent(0x9898, false))
//                    } else {
//                        val intent = Intent()
//                        intent.setClass(activity, MusicService::class.java)
//                        intent.putExtra("MUSIC_ID", data[position].id)
//                        intent.putExtra("MUSIC_PATH", data[position].fileAddress)
//                        intent.putExtra("MUSIC_NAME", data[position].knowledgeTitle)
//                        intent.putExtra("MUSIC_AVATAR", NetConstant.REQUEST_SOURCE + data[position].coverImg)
//                        intent.putExtra("music_state", true)
//                        activity!!.startService(intent)
//                        RxBus.getDefault().post(AudioLayoutVisibleStateEvent(Constant.AUDIO_LAYOUT_VISIBLE_FLAG, true))
//                        RxBus.getDefault().post(MusicPlayNameEvent(0xff21, data[position].knowledgeTitle, NetConstant.REQUEST_SOURCE + data[position].coverImg))
//                        RxBus.getDefault().post(MusicPlayStateEvent(0x9898, false))
//                    }
//                    parentActivity.setPlayState()

                    val audioEntity = AudioEntity(messages[position].id, NetConstant.REQUEST_SOURCE + messages[position].fileAddress, messages[position].knowledgeTitle, NetConstant.REQUEST_SOURCE + messages[position].coverImg)
                    mPlayerManager!!.playMusic(audioEntity)
                }
                3 -> {
                    val intent = Intent()
                    intent.setClass(this, WebActivity::class.java)
                    intent.putExtra("document_url", NetConstant.REQUEST_SOURCE + messages[position].fileAddress)
                    intent.putExtra("document_title", messages[position].knowledgeTitle)
                    intent.putExtra("document_id", messages[position].id)
                    startActivity(intent)
                }
                else -> {

                }
            }
        }
    }

    private fun requestMessage() {
        val hashMap = HashMap<String, Any>()
        hashMap["userId"] = MyApp.instance().userAccount!!.id
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_QUERY_SHARE_MSG)
                .tag(this)
                .upJson(JSONObject(hashMap))
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        srl_refresh.finishRefresh()
                        val jsonObj = JSONObject(response!!.body())
                        val code = jsonObj.getString("code")
                        if (code == "200") {
                            messages.clear()
                            val data = jsonObj.getJSONObject("data")
                            val jsonArray = data.getJSONArray("list")
                            for (i in 0 until jsonArray.length()) {
                                val id = jsonArray.getJSONObject(i).getInt("id")
                                val knowledgeType = jsonArray.getJSONObject(i).getInt("knowledgeType")
                                val knowledgeTitle = jsonArray.getJSONObject(i).getString("knowledgeTitle")
                                val knowledgeContent = jsonArray.getJSONObject(i).getString("knowledgeContent")
                                val knowledgeDescribe = jsonArray.getJSONObject(i).getString("knowledgeDescribe")
                                val knowledgeAuthor = jsonArray.getJSONObject(i).getString("knowledgeAuthor")
                                val coverImg = jsonArray.getJSONObject(i).getString("coverImg")
                                val fileAddress = jsonArray.getJSONObject(i).getString("fileAddress")
                                val browseNumber = jsonArray.getJSONObject(i).getString("browseNumber")
                                val praiseNumber = jsonArray.getJSONObject(i).getInt("praiseNumber")
                                val commentNumber = jsonArray.getJSONObject(i).getString("commentNumber")
                                val specialId = jsonArray.getJSONObject(i).getString("specialId")
                                val createDate = jsonArray.getJSONObject(i).getLong("createDate")
                                val remarks = jsonArray.getJSONObject(i).getString("remarks")
                                val authorName = jsonArray.getJSONObject(i).getString("authorName")
                                val userName = jsonArray.getJSONObject(i).getString("userName")
                                messages.add(ChannelMultipleItemEntity(id, knowledgeType, knowledgeTitle
                                        , knowledgeDescribe, knowledgeContent, knowledgeAuthor, coverImg, praiseNumber, fileAddress, browseNumber,
                                        commentNumber, specialId, createDate, authorName, userName))
                            }
                            if (messages.isEmpty()) {
                                channelListAdapter.emptyView = LayoutInflater.from(this@MessageActivity).inflate(R.layout.view_empty, null)
                            }
                            channelListAdapter.notifyDataSetChanged()
                        }

                    }

                    override fun onError(response: Response<String>?) {
                        srl_refresh.finishRefresh()
                    }
                })
    }


    private fun setOnRecyclerViewScrollDirectListener(rvList: RecyclerView) {
        rvList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                if (dy > 0) {
                    //todo 隐藏播放布局
                    if (Math.abs(dy) > 2) {
                        if (mPlayerManager!!.getPlayerBarVisibilityState()) {
                            mPlayerBarView!!.setPlayerBarVisibility(false)
                        }
                    }

                } else {
                    //todo 显示播放布局
                    if (Math.abs(dy) > 2) {
                        if (mPlayerManager!!.getPlayerBarVisibilityState()) {
                            mPlayerBarView!!.setPlayerBarVisibility(true)
                        }
                    }
                }
            }
        })
    }


    private var conn = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val myBinder = service as (MusicService.MyBinder)
            musicService = myBinder.getService()
            mPlayerManager = musicService!!.getPlayerManager()
            mPlayerBarView = PlayerBarView(this@MessageActivity, mPlayerManager!!, rl_root)
        }
    }

    private fun bindMusicService() {
        val intent = Intent(this, MusicService::class.java)
        bindService(intent, conn, AppCompatActivity.BIND_AUTO_CREATE)
    }


    override fun onDestroy() {
        super.onDestroy()

        if (RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().unregister(this)
        }

        mPlayerBarView = null

        unbindService(conn)
    }
}
